import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Link} from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Popconfirm,
  Tooltip,
  Tabs
} from 'antd';
const {RangePicker} = DatePicker;
const TabPane = Tabs.TabPane;
import StandardTable from 'components/OrderTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {status, statusMap} from './orderStatus';
import SendGoods from './SendGoods';
import {DATA_HOST, HOST} from '../../utils/setting';
import G from '../../utils/g';
import {stringify} from 'qs';

import styles from './OrderList.less';
import Authorized from '../../utils/Authorized';
import {getAuthority} from '../../utils/authority';
import PayType from './PayType';
import {getTimeDistance, getLastDayDistance} from '../../utils/utils';
const FormItem = Form.Item;
const {Option} = Select;
const {TextArea} = Input;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const {modalVisible, form, handleAdd, handleModalVisible} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  return (
    <Modal
      title="新建规则"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{required: true, message: 'Please input some description...'}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>
    </Modal>
  );
});

@connect(({orderList, goodsList, loading}) => ({
  orderList,
  goodsList,
  loading: loading.models.orderList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {
      status: 102
    },
    showSendGoods: false,
    orderId: '',
    activeTabKey: '102',
    rangePickerValue: getLastDayDistance(7), // 默认过去七天
    dateType: 7,
  };

  componentDidMount() {
    const {dispatch} = this.props;
    // dispatch({
    //   type: 'orderList/fetch',
    //   payload: {
    //     status: 102, //默认显示等待发货Tab
    //   }
    // });
    this.selectDate(7); //默认显示过去七天
    dispatch({
      type: 'orderList/getStatusCount' //获取订单数量
    });
    if (getAuthority() == 'admin') { //管理员需要获取商家列表
      dispatch({
        type: 'goodsList/getShopList',
      });
    }
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: ( pagination.current - 1 ) * pagination.pageSize,  //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'orderList/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      formValues: {
        status: 102
      },
      activeTabKey: "102"
    });
    dispatch({
      type: 'orderList/fetch',
      payload: {
        status: 102
      },
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const {dispatch} = this.props;
    const {selectedRows} = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'orderList/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {

    e && e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      if (Array.isArray(fieldsValue.time)) {
        values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
        values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
      }
      delete values.time;

      this.setState({
        formValues: values,
        activeTabKey: [102, 100, 103, 200, 105].includes(Number(values.status)) ? values.status : "1"
      });

      dispatch({
        type: 'orderList/fetch',
        payload: values,
      });

      dispatch({
        type: 'orderList/getStatusCount', //获取订单数量
        payload: values,
      });
    });
  };

  handleExportOrder = ()=> { //导出查询订单
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        token: window.localStorage.token
      };
      if (Array.isArray(fieldsValue.time)) {
        values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
        values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
      }
      delete values.time;
      const sign = G.md5Encrypt(values);
      const href = DATA_HOST + '/dashboard/excel/order/?' + stringify(values) + '&sign=' + sign
      console.log('href', href);
      window.open(href);
    })
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'orderList/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  handleShowSendGoods = (id)=> {
    this.setState({
      showSendGoods: true,
      orderId: id,
    });
  };

  bindHideSendGoods = ()=> {
    this.setState({
      showSendGoods: false,
    });
  };

  bindChangeInfo = (params)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'orderList/changeInfo',
      payload: params
    });
  };

  openDetail = (id)=> {
    G.openPc(`${HOST}/shop/admin/#/goods/goods-add?id=${id}`);
  }

  renderForm() {
    const {getFieldDecorator} = this.props.form;
    console.log(this.props);
    const {shopList} = this.props.goodsList;
    let statusList = [];
    for (let k in status) {
      statusList.push(<Option value={k} key={k}>{ status[k] }</Option>);
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="订单号">
              {getFieldDecorator('orderId')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('phone')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

        </Row>
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="下单时间">
              {getFieldDecorator('time')(
                <RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']}/>
              )}
            </FormItem>
          </Col>
          <Authorized authority="admin">
            <Col md={8} sm={24}>
              <FormItem label="商家列表">
                {getFieldDecorator('business_id')(
                  <Select placeholder="请选择" style={{width: '100%'}}>
                    {
                      shopList.map(v=> {
                        return <Option value={v.userId}
                                       key={'business' + v.userId}>{v.userInfo.nickname}</Option>
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
          </Authorized>
          <Col md={8} sm={24}>
            <FormItem label="订单状态">
              {getFieldDecorator('status', {
                initialValue: '102',
              })(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  {
                    statusList
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleExportOrder}>
                报表导出
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  tabChange = (key) => {  //Tab切换
    console.log(key);
    const {setFieldsValue} = this.props.form;
    if (key != 1) {
      setFieldsValue({
        status: key
      });
    } else {
      setFieldsValue({
        status: ''
      });
    }
    this.handleSearch();
  }

  selectDate = type => {
    // console.log(getLastDayDistance(7));
    this.setState({
      dateType: type,
      rangePickerValue: getLastDayDistance(type),
    }, ()=> {
      const {rangePickerValue} = this.state;
      const {form : {setFieldsValue}} = this.props;
      if (type) {
        setFieldsValue({'time': rangePickerValue});
      } else {
        setFieldsValue({'time': ''});
      }
      this.handleSearch();
    });

  };

  isActive = (type)=> {
    const {dateType} = this.state;
    if (type == dateType) {
      return styles.currentDate;
    } else {
      return;
    }
  }

  render() {
    const {orderList: {data, orderDetail, statusCount}, loading} = this.props;
    const {selectedRows, modalVisible, showSendGoods, orderId, activeTabKey, rangePickerValue} = this.state;
    const _this = this;

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    const columns = [
      {
        title: '订单号',
        dataIndex: 'orderId',
        key: 'orderId',
        width: 80,
        render(text, record){
          let result = text.toString();
          return <Link to={`order-detail?id=${record.orderId}`}>{result.substr(result.length - 4)}</Link>; //取后四位显示
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 80,
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]}/>;
        },
      },
      {
        title: '商品',
        width: 300,
        render(text, record) {

          return record.order_goods.map((goods)=> {
            let sku = '';
            for (let key in goods.sku) {
              sku += key + ':' + goods.sku[key] + ' ';
            }
            return <a key={record.orderId + goods.id} onClick={()=> {
              _this.openDetail(goods.goodsId)
            }}>
              <img className={styles.goodsPic} src={`${goods.img}?imageView2/1/w/50`} width={50} />
              <p className={styles.goodsName}>
                {goods.name} × {goods.count}<br/>
                <span className={styles.goodsColor}>{
                  sku
                }</span>
              </p>
            </a>
          })
        },
      },
      {
        title: '实付/总金额/优惠',
        width: 200,
        render(val, record){
          return (
          <div>
            <Tooltip
              title={`${PayType[record.pay_type]}`}><b style={{color: '#3f92a2'}}><Icon
              type="info-circle-o"/> {record.paid_price}</b>
            </Tooltip>
            / {record.originalPrice} / <Tooltip
            title={`促销优惠：${record.promotionPrice},优惠券优惠：${record.couponPrice}`}><Icon
            type="info-circle-o"/> {(Number(record.promotionPrice) + Number(record.couponPrice)).toFixed(2)}
          </Tooltip>
          </div>
          )
        }
      },
      {
        title: '买家信息',
        align: 'right',
        render: (val, record)=> {
          return (<div>
            {record.nickname}<br/>
            {record.addressee} / {record.phone}
          </div>);
        }
      },
      {
        title: '下单时间',
        dataIndex: 'createTime',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '买家备注',
        dataIndex: 'buy_message',
      },
      {
        title: '操作',
        render: (text, record) => {
          return <Fragment>
            <Popconfirm title={<TextArea id={`remark${record.orderId}`} rows={4} placeholder="请输入你想备注的信息"
                                         defaultValue={record.remark}/>} okText="确定" cancelText="取消"
                        onConfirm={()=> {
                          this.bindChangeInfo({
                            orderId: record.orderId,
                            remark: document.getElementById(`remark${record.orderId}`).value
                          })
                        }}>
              <a href="#">备注</a>
            </Popconfirm>
            <Divider type="vertical"/>
            {record.status == 100 ? <span>
          <Popconfirm title="你确定要取消此订单？" okText="确定" cancelText="取消" onConfirm={()=> {
            this.bindChangeInfo({orderId: record.orderId, status: 105})
          }}>
            <a href="#">取消订单</a>
          </Popconfirm>
          <Divider type="vertical"/>
          <Popconfirm title={<Input placeholder="请输入新的订单价格" id={`newPrice${record.orderId}`}/>} okText="确定"
                      cancelText="取消" onConfirm={(e)=> {
            this.bindChangeInfo({
              orderId: record.orderId,
              price: document.getElementById(`newPrice${record.orderId}`).value
            })
          }}>
            <a href="#">修改价格</a>
          </Popconfirm>
          <Divider type="vertical"/>
          </span> : null}
            {record.status == 103 ? <span>
          <Popconfirm title="你确定要延长一周的收货时间吗？" okText="确定" cancelText="取消" onConfirm={()=> {
            this.bindChangeInfo({orderId: record.orderId, receipt_days: 7})
          }}>
            <a href="javascript:;">延长收货</a>
          </Popconfirm>
          <Divider type="vertical"/>
          <a href="javascript:;" onClick={()=> {
            this.handleShowSendGoods(record.orderId)
          }}>修改物流</a>
          <Divider type="vertical"/>
          </span> : null}
            {record.status == 102 ? <span><a onClick={()=> {
              this.handleShowSendGoods(record.orderId)
            }}>发货</a><Divider type="vertical"/></span> : null}
            <Link to={`order-detail?id=${record.orderId}`}>详情</Link>
          </Fragment>
        }
      },
    ];

    const dateSelect = (<div className={styles.salesExtraWrap}>
      <div className={styles.salesExtra}>

        <a className={this.isActive('7')} onClick={() => this.selectDate('7')}>
          过去七天
        </a>
        <a className={this.isActive('30')} onClick={() => this.selectDate('30')}>
          过去三十天
        </a>
        <a className={this.isActive('90')} onClick={() => this.selectDate('90')}>
          过去九十天
        </a>
        <a className={this.isActive('all')} onClick={() => this.selectDate()}>
          全部
        </a>
        {/*<a className={this.isActive('year')} onClick={() => this.selectDate('year')}>
          全年
        </a>*/}
      </div>
    </div>);

    return (
      <div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {/*<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
               新建
               </Button>*/}
            </div>
            <Tabs
              defaultActiveKey="102"
              onChange={this.tabChange}
              type="card"
              activeKey={activeTabKey}
              tabBarExtraContent={dateSelect}
            >
              <TabPane tab={`待发货(${statusCount['102']})`} key="102">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={102 + 'orderId'}
                />
              </TabPane>
              <TabPane tab={`已发货(${statusCount['103']})`} key="103">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={103 + 'orderId'}
                />
              </TabPane>
              <TabPane tab={`申请退款(${statusCount['200']})`} key="200">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={200 + 'orderId'}
                />
              </TabPane>
              {
                getAuthority() == 'admin' ? <TabPane tab={`等待付款(${statusCount['100']})`} key="100">
                  <StandardTable
                    loading={loading}
                    data={data}
                    columns={columns}
                    onChange={this.handleStandardTableChange}
                    rowKey={100 + 'orderId'}
                  />
                </TabPane> : null
              }
              <TabPane tab={`交易完成(${statusCount['104']})`} key="104">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={104 + 'orderId'}
                />
              </TabPane>
              <TabPane tab={`交易关闭(${statusCount['105']})`} key="105">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={105 + 'orderId'}
                />
              </TabPane>
              <TabPane tab={`全部(${statusCount['1']})`} key="1">
                <StandardTable
                  loading={loading}
                  data={data}
                  columns={columns}
                  onChange={this.handleStandardTableChange}
                  rowKey={1 + 'orderId'}
                />
              </TabPane>
            </Tabs>
            {/*expandedRowRender={record => <p style={{margin: 0}}>卖家备注：{record.remark}</p>}*/}
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible}/>
        <SendGoods dispatch={this.props.dispatch} show={showSendGoods} data={orderDetail}
                   hideSendGoods={ this.bindHideSendGoods } id={orderId}
                   sendDispatchType="orderList/sendGoods"/>
      </div>
    );
  }
  }
